import axios from "axios";

/*
 * 天气api
 */
const saveSession = data => {
  sessionStorage.setItem("weather_data", JSON.stringify(data));
};
const getSession = () => {
  return JSON.parse(sessionStorage.getItem("weather_data"));
};
const url =
  "https://www.tianqiapi.com/api/?version=v6&appid=42948694&appsecret=K3lKg4fv";
export default function getWeather() {
  return new Promise((resolve, reject) => {
    if (sessionStorage) {
      let data = getSession();
      if (data) {
        resolve(data);
      } else {
        axios
          .get(url)
          .then(res => {
            if (res.status === 200) {
              saveSession(res.data);
              resolve(res.data);
            } else {
              reject(res);
            }
          })
          .catch(err => {
            reject(err);
          });
      }
    } else {
      axios
        .get(url)
        .then(res => {
          if (res.status === 200) {
            saveSession(res.data);
            resolve(res.data);
          } else {
            reject(res);
          }
        })
        .catch(err => {
          reject(err);
        });
    }
  });
}
